package com.zjitc.pigspring.job;


import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Slf4j
public class BackUpSqlJob extends QuartzJobBean {

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.ip}")
    private String ip;

    @Value("${spring.mysql.port}")
    private String port;



    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("Job start.............");

// 使用 ProcessBuilder 而不是直接拼接字符串来执行命令 -=
        ProcessBuilder processBuilder = new ProcessBuilder("mysqldump", "-u", username, "--password=" + password, "-h",ip, "-P", port, "-Q", "store", "-r", "backup.sql");

        try {
            Process process = processBuilder.start();

            // 读取标准输出
            new Thread(() -> {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line); // 或者将输出记录到日志中
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 读取标准错误
            new Thread(() -> {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        System.err.println(line); // 或者将错误记录到日志中
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Backup completed successfully.");
            } else {
                System.err.println("Backup failed with exit code: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
